<?php
class MSA_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		$auth = Zend_Auth::getInstance();
		$this->recoveryAuth($auth);
		$controller = $request->getControllerName();
		$action = $request->getActionName();
		
		if ($controller == 'utility' || $controller == 'error') return;
		
		if (!$auth->hasIdentity()) {
			if ( ($controller == 'user' && $action == 'login') ) {
				
			}
			else {
				$request->setControllerName('user');
				$request->setActionName('login');
			}
		}
	}
	
	/**
	 * 
	 * 从cookie中获取登录凭据
	 * @param Zend_Auth $auth
	 */
	private function recoveryAuth($auth)
	{
		$token = isset($_COOKIE['token'])?$_COOKIE['token']:'';
		$id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'';
		if (empty($token) || empty($id)) {
			$auth->clearIdentity();
			return;
		}
		
		$dbAdapter = Zend_Db_Table::getDefaultAdapter();
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter, 'admin_user', 'id', 'token');
		$authAdapter->setIdentity($id);
		$authAdapter->setCredential($token);
		$result = $authAdapter->authenticate();
		if ($result->isValid()) {
			$storage = $auth->getStorage();
			$storage->write( $authAdapter->getResultRowObject( array('id', 'role_id', 'username') ) );
		}
		else {
			$auth->clearIdentity();
		}
	}
}